package com.neu.credit.creditscore.controller;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.neu.credit.creditscore.common.utils.Result;
import com.neu.credit.creditscore.dto.req.AddDepartmentReq;
import com.neu.credit.creditscore.dto.req.DrugSaveReq;
import com.neu.credit.creditscore.dto.req.ExamSaveReq;
import com.neu.credit.creditscore.dto.req.HospitalPreOrderReq;
import com.neu.credit.creditscore.dto.res.book.BooksPageListRes;
import com.neu.credit.creditscore.dto.res.hospital.*;
import com.neu.credit.creditscore.entity.hospital.Departments;
import com.neu.credit.creditscore.entity.hospital.Doctors;
import com.neu.credit.creditscore.entity.hospital.ExaminationItems;
import com.neu.credit.creditscore.service.hospital.DoctorsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/hospital")
@Tag(name = "医院管理系统", description = "医院科室、医生、预约、诊断等相关接口") // 替换 @Api
@Slf4j
public class HospitalController {

    @Autowired
    private DoctorsService doctorsService;
    @PostMapping("/login")
    public Result<Map<String, Object>> login(
            @RequestParam("phone") String  phone,
            @RequestParam("password") String password
    ) {
        // 参数校验
        if (StringUtils.isBlank(phone) || StringUtils.isBlank(password)) {
            return Result.error("电话和密码不能为空");
        }
        Doctors doctor= doctorsService.validateLogin(phone, password);
        if (doctor == null) {
            // 失败场景2：手机号不存在或密码错误
            return Result.error("手机号或密码错误");
        }
        Map<String, Object> data = new HashMap<>();
        data.put("doctorId", doctor.getId());
        data.put("doctorName",doctor.getDoctorName());
        return  Result.success("登录成功",data);
    }

    @GetMapping("/recommend")
    @Operation(summary = "获取推荐的主任医生", description = "获取首页推荐的主任医生列表")
    public Result<List<RecommendDoctorsRes>> getRecommendDoctor() {
        try {
            return doctorsService.getRecommendDoctor();
        } catch (Exception e) {
            log.error("getRecommendDoctor has a error", e);
            return Result.error("获取推荐的主任医生失败！");
        }
    }

    @GetMapping("/department/list")
    @Operation(summary = "获取科室列表", description = "根据科室类型获取科室列表")
    public Result<List<Departments>> getDepartments(
            @Parameter(description = "科室类型 (1:门诊, 2:医技)", required = true)
            @RequestParam("departmentType") int departmentType) {
        try {
            return doctorsService.getDepartments(departmentType);
        } catch (Exception e) {
            log.error("getDepartments has a error", e);
            return Result.error("获取科室失败！");
        }
    }

    @GetMapping("/doctors/list")
    @Operation(summary = "获取医生列表", description = "根据科室ID获取医生列表")
    public Result<DoctorListInfoRes> getDoctors(
            @Parameter(description = "科室ID", required = true)
            @RequestParam("departmentId") int departmentId) {
        try {
            return doctorsService.getDoctors(departmentId);
        } catch (Exception e) {
            log.error("getDoctors has a error", e);
            return Result.error("获取医生列表失败！");
        }
    }

    @GetMapping("/doctors/details")
    @Operation(summary = "获取医生详细信息", description = "根据医生ID获取详细信息")
    public Result<Doctors> getDoctorsDetail(
            @Parameter(description = "医生ID", required = true)
            @RequestParam("doctorId") int doctorId) {
        try {
            return doctorsService.getDoctorsDetail(doctorId);
        } catch (Exception e) {
            log.error("getDoctorsDetail has a error", e);
            return Result.error("获取医生详情失败！");
        }
    }

    @PostMapping("/pre/order")
    @Operation(summary = "患者预约预下单", description = "生成预约预订单信息")
    public Result<HospitalPreOrderInfoRes> getPreOrderInfo(
            @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "预约请求参数")
            @RequestBody HospitalPreOrderReq hospitalPreOrderReq,@RequestParam("id") Integer id) {
        try {
            return doctorsService.getPreOrderInfo(hospitalPreOrderReq,id);
        } catch (Exception e) {
            log.error("getPreOrderInfo has a error", e);
            return Result.error("医院预约预下单失败！");
        }
    }

    @GetMapping("/order")
    @Operation(summary = "患者确定预约", description = "确认预约并生成正式订单")
    public Result<String> order(
            @Parameter(description = "预约ID", required = true)
            @RequestParam("appointmentId") int appointmentId) {
        try {
            return doctorsService.order(appointmentId);
        } catch (Exception e) {
            log.error("order has a error", e);
            return Result.error("医院预约下单失败！");
        }
    }

    @GetMapping("/order/list")
    @Operation(summary = "我的预约列表", description = "获取当前用户的预约记录")
    public Result<List<MyAppointmentRes>> orderMyList(@RequestParam("id") Integer id) {
        try {
            List<MyAppointmentRes> list = doctorsService.orderMyList(id).getData();
            return Result.success(list);
        } catch (Exception e) {
            log.error("orderMyList has a error", e);
            return Result.error("获取我的预约列表失败！");
        }
    }

    @GetMapping("/cancel/appoint/{appointmentId}")
    @Operation(summary = "取消预约", description = "根据预约ID取消预约")
    public Result<String> cancelAppoint(
            @Parameter(description = "预约ID", required = true)
            @PathVariable("appointmentId") int appointmentId) {
        try {
            return doctorsService.cancelAppoint(appointmentId);
        } catch (Exception e) {
            log.error("cancelAppoint has a error", e);
            return Result.error("取消预约失败！");
        }
    }

    @GetMapping("/patients/list")
    @Operation(summary = "获取患者列表", description = "根据医生Id查询患者列表")
    public Result<List<PatientInfoRes>> getPatientsList(
            @Parameter(description = "医生Id")
            @RequestParam(name = "doctorId", defaultValue = "医生id")  Integer  id) {
        try {
            return doctorsService.getPatientsList(id);
        } catch (Exception e) {
            log.error("getPatientsList has a error", e);
            return Result.error("获取患者列表失败！");
        }
    }
    @GetMapping("/patients/search")
    @Operation(summary = "获取患者列表",description = "根据医生ID和患者姓名搜索患者列表")
    public Result<List<PatientInfoRes>> searchPatientsByName(
            @RequestParam Integer doctorId,
            @RequestParam String patientName
    ) {
        try
        {
            return doctorsService.searchPatientsByName(doctorId, patientName);
        } catch (Exception e) {
            log.error("getPatientsList has a error", e);
            return Result.error("获取患者列表失败！");
        }
    }

    @GetMapping("/checking")
    @Operation(summary = "获取当前接诊患者信息", description = "获取医生正在接诊的患者信息")
    public Result<PatientInfoRes> getCheckNow() {
        try {
            return doctorsService.getCheckNow();
        } catch (Exception e) {
            log.error("startCheck has a error", e);
            return Result.error("获取失败！");
        }
    }

    @GetMapping("/start/check")
    @Operation(summary = "开始接诊", description = "开始接诊指定患者")
    public Result<String> startCheck(
            @Parameter(description = "患者ID", required = true)
            @RequestParam("patientId") int patientId,@RequestParam("doctorId") int doctorId) {
        try {
            return doctorsService.startCheck(patientId,doctorId);
        } catch (Exception e) {
            log.error("startCheck has a error", e);
            return Result.error("开始接诊失败！");
        }
    }

    @GetMapping("/finish/check")
    @Operation(summary = "结束接诊", description = "结束当前接诊")
    public Result<String> finishCheck(
            @Parameter(description = "患者ID", required = true)
            @RequestParam("patientId") int patientId,@RequestParam("doctorId") int doctorId) {
        try {
            return doctorsService.finishCheck(patientId,doctorId);
        } catch (Exception e) {
            log.error("finishCheck has a error", e);
            return Result.error("结束接诊失败！");
        }
    }

    @GetMapping("/examination/list")
    @Operation(summary = "获取检查项目列表", description = "根据科室和项目名称查询")
    public Result<ExaminationInfoRes> getExamList(
            @Parameter(description = "科室ID (0表示全部)")
            @RequestParam(name = "departmentId", defaultValue = "0") int departmentId,
            @Parameter(description = "检查项目名称")
            @RequestParam(name = "itemName", defaultValue = "") String itemName,
            @Parameter(description = "患者ID", required = true)
            @RequestParam int patientId) {
        try {
            return doctorsService.getExamList(departmentId, itemName, patientId);
        } catch (Exception e) {
            log.error("getExamList has a error", e);
            return Result.error("获取检查项目列表失败！");
        }
    }

    @PostMapping("/save/examination")
    @Operation(summary = "保存检查项目", description = "保存患者检查项目清单")
    public Result<String> saveExamList(
            @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "检查项目请求参数")
            @RequestBody ExamSaveReq examSaveReq,@RequestParam(name = "doctorId", defaultValue = "医生id") Integer  id) {
        try {
            return doctorsService.saveExamList(examSaveReq,id);
        } catch (Exception e) {
            log.error("saveExamList has a error", e);
            return Result.error("保存检查项目失败！");
        }
    }

    @GetMapping("/drug/list")
    @Operation(summary = "获取药品列表", description = "根据药品名称查询")
    public Result<DrugInfoRes> getDrug(
            @Parameter(description = "药品名称")
            @RequestParam(name = "drugName", defaultValue = "") String drugName,
            @Parameter(description = "患者ID", required = true)
            @RequestParam("patientId") int patientId) {
        try {
            return doctorsService.getDrug(drugName, patientId);
        } catch (Exception e) {
            log.error("getDrug has a error", e);
            return Result.error("获取药品列表失败！");
        }
    }

    @PostMapping("/save/drug")
    @Operation(summary = "保存处方药品", description = "保存患者处方药品清单")
    public Result<String> saveDrug(
            @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "药品请求参数")
            @RequestBody DrugSaveReq drugSaveReq, @RequestParam(name = "doctorId", defaultValue = "医生id")  Integer  id) {
        try {
            return doctorsService.saveDrug(drugSaveReq,id);
        } catch (Exception e) {
            log.error("saveDrug has a error", e);
            return Result.error("保存药品失败！");
        }
    }

    @GetMapping("/save/diagnosis")
    @Operation(summary = "保存诊断结果", description = "保存患者的诊断结果")
    public Result<String> saveDiagnosis(
            @Parameter(description = "患者ID", required = true)
            @RequestParam("patientId") int patientId,
            @Parameter(description = "诊断结果", required = true)
            @RequestParam("diagnosisResult") String diagnosisResult ) {
        try {
            return doctorsService.saveDiagnosis(patientId, diagnosisResult );
        } catch (Exception e) {
            log.error("saveDiagnosis has a error", e);
            return Result.error("保存诊断结果失败！");
        }
    }

    @GetMapping("/result/detail")
    @Operation(summary = "获取诊断结果详情", description = "根据预约ID获取诊断详情")
    public Result<ResultDetailRes> getResultDetail(
            @Parameter(description = "预约ID", required = true)
            @RequestParam("appointmentId") int appointmentId,@RequestParam("id") Integer id) {
        try {

            Result<ResultDetailRes> detail = doctorsService.getResultDetail(appointmentId, id);
            System.out.println(detail.getData().getAppointments());
            System.out.println(detail.getData().getDiagnosisResult());
            System.out.println(detail.getData().getFees());
            System.out.println(detail.getData().getDiagnosisRecords());
            System.out.println(detail.getData().getOrders());
            return detail;
        } catch (Exception e) {
            log.error("saveDiagnosis has a error", e);
            return Result.error("获取失败！");
        }
    }

    @GetMapping("/pre/fee")
    @Operation(summary = "获取预支付信息", description = "获取治疗费用预支付信息")
    public Result<PreFeeRes> prePayFee(
            @Parameter(description = "预约ID", required = true)
            @RequestParam("appointmentId") int appointmentId) {
        try {
            return doctorsService.prePayFee(appointmentId);
        } catch (Exception e) {
            log.error("prePayFee has a error", e);
            return Result.error("预支付失败！");
        }
    }

    @GetMapping("/pay/fee")
    @Operation(summary = "支付治疗费用", description = "确认支付治疗费用")
    public Result<String> payFee(
            @Parameter(description = "费用ID", required = true)
            @RequestParam("feeId") int feeId  ) {
        try {

            return doctorsService.payFee(feeId );
        } catch (Exception e) {
            log.error("payFee has a error", e);
            return Result.error("支付失败！");
        }
    }

    @GetMapping("/admin/department/list")
    @Operation(summary = "获取科室分页列表", description = "管理员获取科室分页数据")
    public Result<DepartmentPageRes> getDepartmentList(
            @Parameter(description = "页码", example = "1")
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @Parameter(description = "每页数量", example = "10")
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
            @Parameter(description = "科室ID (0表示全部)")
            @RequestParam(value = "departmentId", defaultValue = "0") int departmentId,
            @Parameter(description = "科室名称")
            @RequestParam(value = "departmentName", defaultValue = "") String departmentName) {
        try {
            return doctorsService.getDepartmentList(pageNum, pageSize, departmentId, departmentName);
        } catch (Exception e) {
            log.error("getDepartmentList has a error", e);
            return Result.error("获取科室分页失败！");
        }
    }

    @PostMapping("/add/fee")
    @Operation(summary = "添加科室", description = "管理员添加新科室")
    public Result<String> addDepartment(
            @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "科室信息")
            @RequestBody AddDepartmentReq addDepartmentReq) {
        try {
            return doctorsService.addDepartment(addDepartmentReq);
        } catch (Exception e) {
            log.error("addDepartment has a error", e);
            return Result.error("添加失败！");
        }
    }

    @GetMapping("/department/detail/{departmentId}")
    @Operation(summary = "获取科室详情", description = "根据科室ID获取详情")
    public Result<Departments> getDepartmentDetail(
            @Parameter(description = "科室ID", required = true)
            @PathVariable("departmentId") int departmentId) {
        try {
            return doctorsService.getDepartmentDetail(departmentId);
        } catch (Exception e) {
            log.error("getDepartmentDetail has a error", e);
            return Result.error("获取失败！");
        }
    }

    @PostMapping("/department/update")
    @Operation(summary = "编辑科室", description = "更新科室信息")
    public Result<String> updateDepartment(
            @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "科室信息")
            @RequestBody Departments departments) {
        try {
            return doctorsService.updateDepartment(departments);
        } catch (Exception e) {
            log.error("updateDepartment has a error", e);
            return Result.error("编辑失败！");
        }
    }

    @GetMapping("/department/deleted/{departmentId}")
    @Operation(summary = "删除科室", description = "根据科室ID删除科室")
    public Result<String> deletedDepartment(
            @Parameter(description = "科室ID", required = true)
            @PathVariable("departmentId") int departmentId) {
        try {
            return doctorsService.deletedDepartment(departmentId);
        } catch (Exception e) {
            log.error("deletedDepartment has a error", e);
            return Result.error("删除失败！");
        }
    }

    @GetMapping("/admin/doctor/list")
    @Operation(summary = "获取医生分页列表", description = "管理员获取医生分页数据")
    public Result<DoctorListRes> getDoctorList(
            @Parameter(description = "页码", example = "1")
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @Parameter(description = "每页数量", example = "10")
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
            @Parameter(description = "医生ID (0表示全部)")
            @RequestParam(value = "doctorId", defaultValue = "0") int doctorId,
            @Parameter(description = "医生姓名")
            @RequestParam(value = "doctorName", defaultValue = "") String doctorName) {
        try {
            return doctorsService.getDoctorList(pageNum, pageSize, doctorId, doctorName);
        } catch (Exception e) {
            log.error("getDoctorList has a error", e);
            return Result.error("获取医生分页失败！");
        }
    }

    @PostMapping("/add/doctor")
    @Operation(summary = "添加医生", description = "管理员添加新医生")
    public Result<String> addDoctor(
            @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "医生信息")
            @RequestBody Doctors doctors ) {
        try {
            return doctorsService.addDoctor(doctors );
        } catch (Exception e) {
            log.error("addDoctor has a error", e);
            return Result.error("添加失败！");
        }
    }

    @GetMapping("/deleted/doctor/{doctorId}")
    @Operation(summary = "删除医生", description = "根据医生ID删除医生")
    public Result<String> deletedDoctor(
            @Parameter(description = "医生ID", required = true)
            @PathVariable("doctorId") int doctorId) {
        try {
            return doctorsService.deletedDoctor(doctorId);
        } catch (Exception e) {
            log.error("deletedDoctor has a error", e);
            return Result.error("删除失败！");
        }
    }

    @GetMapping("/doctor/detail/{doctorId}")
    @Operation(summary = "获取医生详情", description = "根据医生ID获取详情")
    public Result<Doctors> getDoctorDetail(
            @Parameter(description = "医生ID", required = true)
            @PathVariable("doctorId") int doctorId) {
        try {
            return doctorsService.getDoctorDetail(doctorId);
        } catch (Exception e) {
            log.error("getDoctorDetail has a error", e);
            return Result.error("获取失败！");
        }
    }

    @PostMapping("/doctor/update")
    @Operation(summary = "编辑医生信息", description = "更新医生信息")
    public Result<String> updateDoctor(
            @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "医生信息")
            @RequestBody Doctors doctors) {
        try {
            return doctorsService.updateDoctor(doctors );
        } catch (Exception e) {
            log.error("updateDoctor has a error", e);
            return Result.error("编辑失败！");
        }
    }
}